<script lang="ts" setup>
import {onMounted} from 'vue';
import {useRoute} from 'vue-router';
import {useArticleListStore} from '@/stores/articleListStore';
import ArticleListLayout from "@/layouts/ArticleListLayout.vue";
import ArticleListPagination from "@/components/pageElement/ArticleListPagination.vue";
import {formatDate} from "@/utils/tools";

const props = withDefaults(defineProps<{
  name: string;
  isPdf?: boolean;
}>(), {
  isPdf: false
});

const route = useRoute();
const articleListStore = useArticleListStore();

// 设置分类并加载当前页
articleListStore.articleCategory = props.name

onMounted(async () => {
  const page = route.query.page ? parseInt(route.query.page as string, 10) : articleListStore.currentPage;

  await articleListStore.loadArticles(page);

  const articleId = parseInt(route.query.articleId as string, 10);
  if (articleId) {
    await articleListStore.setCurrentArticleIndex(articleId);
    await articleListStore.loadPrevNextPages(); // 根据当前文章索引加载前后页数据
  }
});

const handlePageChange = async (newPage: number) => {
  await articleListStore.loadArticles(newPage);
  window.history.pushState({}, "", `?page=${newPage}`);
};
</script>

<template>
  <article-list-layout>
    <div id="article_list">
      <ul class="listrx">
        <li v-for="(article) in articleListStore.articleList" :key="article.id">
          <h6 class="fr">{{ formatDate(article.createTime) }}</h6>
          <NuxtLink
              :title="article.title"
              :to="{ name:isPdf?n2r('PDF文章'):n2r('常规文章') , query: { articleId: article.id } }"
              @click="setLocationByName(name)"
          >
            {{ article.title }}
          </NuxtLink>
        </li>
      </ul>
      <article-list-pagination
          :current-page="articleListStore.currentPage"
          :total-pages="Math.ceil(articleListStore.articleList.length / articleListStore.pageSize)"
          @change="handlePageChange"
      />
    </div>
  </article-list-layout>
</template>
